﻿// ==UserScript==
// @name        Ultimate Fighting Script Platinum
// @namespace   ufs_platinum
// @description Ultimate Fighting Script for Mafiawars Game
// @include     http://facebook.mafiawars.zynga.com/mwfb/remote/html_server.php*
// @include     http://mwfb.zynga.com/mwfb/remote/html_server.php*
// @include     http://facebook.mafiawars.zynga.com/mwfb/xd_receiver.htm
// @include     http://apps.facebook.com/inthemafia/*
// @include     http://apps.new.facebook.com/inthemafia/*
// @include     http://www.facebook.com/connect/uiserver*
// @include     https://www.facebook.com/dialog/feed*
// @exclude     http://mwfb.zynga.com/mwfb/*#*
// @exclude     http://facebook.mafiawars.zynga.com/mwfb/*#*
// @exclude     http://apps.facebook.com/inthemafia/sk_updater.php*
// @exclude	    http://facebook.mafiawars.zynga.com/mwfb/iframe_proxy.php*
// @include     https://facebook.mafiawars.zynga.com/mwfb/remote/html_server.php*
// @include     https://mwfb.zynga.com/mwfb/remote/html_server.php*
// @include     https://facebook.mafiawars.zynga.com/mwfb/xd_receiver.htm
// @include     https://apps.facebook.com/inthemafia/*
// @include     https://apps.new.facebook.com/inthemafia/*
// @include     https://www.facebook.com/connect/uiserver*
// @exclude     https://mwfb.zynga.com/mwfb/*#*
// @exclude     https://facebook.mafiawars.zynga.com/mwfb/*#*
// @exclude     https://apps.facebook.com/inthemafia/sk_updater.php*
// @exclude	    https://facebook.mafiawars.zynga.com/mwfb/iframe_proxy.php*
// @version     3.0.2
// ==/UserScript==


function injectScript(source) {
    // Utilities
    var isFunction = function (arg) {
            return (Object.prototype.toString.call(arg) == "[object Function]");
        };
    var jsEscape = function (str) {
            // Replaces quotes with numerical escape sequences to
            // avoid single-quote-double-quote-hell, also helps by escaping HTML special chars.
            if (!str || !str.length) return str;
            // use \W in the square brackets if you have trouble with any values.
            var r = /['"<>\/]/g,
                result = "",
                l = 0,
                c;
            do {
                c = r.exec(str);
                result += (c ? (str.substring(l, r.lastIndex - 1) + "\\x" + c[0].charCodeAt(0).toString(16)) : (str.substring(l)));
            } while (c && ((l = r.lastIndex) > 0))
            return (result.length ? result : str);
        };
    var bFunction = isFunction(source);
    var elem = document.createElement("script"); // create the new script element.
    var script, ret, id = "";
    if (bFunction) {
        // We're dealing with a function, prepare the arguments.
        var args = [];
        for (var i = 1; i < arguments.length; i++) {
            var raw = arguments[i];
            var arg;
            if (isFunction(raw)) // argument is a function.
            arg = "eval(\"" + jsEscape("(" + raw.toString() + ")") + "\")";
            else if (Object.prototype.toString.call(raw) == '[object Date]') // Date
            arg = "(new Date(" + raw.getTime().toString() + "))";
            else if (Object.prototype.toString.call(raw) == '[object RegExp]') // RegExp
            arg = "(new RegExp(" + raw.toString() + "))";
            else if (typeof raw === 'string' || typeof raw === 'object') // String or another object
            arg = "JSON.parse(\"" + jsEscape(JSON.stringify(raw)) + "\")";
            else arg = raw.toString(); // Anything else number/boolean
            args.push(arg); // push the new argument on the list
        }
        // generate a random id string for the script block
        while (id.length < 16) id += String.fromCharCode(((!id.length || Math.random() > 0.5) ? 0x61 + Math.floor(Math.random() * 0x19) : 0x30 + Math.floor(Math.random() * 0x9)));
        // build the final script string, wrapping the original in a boot-strapper/proxy:
        script = "(function(){var value={callResult: null, throwValue: false};try{value.callResult=((" + source.toString() + ")(" + args.join() + "));}catch(e){value.throwValue=true;value.callResult=e;};" + "document.getElementById('" + id + "').innerText=JSON.stringify(value);})();";
        elem.id = id;
    } else // plain string, just copy it over.
    {
        script = source;
    }
    elem.type = "text/javascript";
    elem.innerHTML = script;
    // insert the element into the DOM (it starts to execute instantly)
    document.head.appendChild(elem);
    if (bFunction) {
        // get the return value from our function:
        ret = JSON.parse(elem.innerText);
        // remove the now-useless clutter.
        elem.parentNode.removeChild(elem);
        // make sure the garbage collector picks it instantly. (and hope it does)
        delete(elem);
        // see if our returned value was thrown or not
        if (ret.throwValue) throw (ret.callResult);
        else return (ret.callResult);
    } else // plain text insertion, return the new script element.
    return (elem);
};

var myscript = function (){
	var is_chrome = navigator.userAgent.toLowerCase().indexOf("chrome") > - 1;
    if (document.getElementById("pagelet_ticker")) {
        var ticker = document.getElementById("pagelet_ticker");
        var ego_pane = document.getElementById("pagelet_ego_pane");
        ticker.parentNode.removeChild(ticker);
        ego_pane.parentNode.removeChild(ego_pane);
        return;
    }
	
	if (navigator.appName == 'Microsoft Internet Explorer') {
		alert('You are using Internet Explorer, this bookmarklet will not work.\nUse Firefox or Chrome instead.');
		return;
	}
	if (/m.mafiawars.com/.test(document.location)) {
		window.location.href = document.location+'?iframe=1';
	}
	else if (/apps.facebook.com.inthemafia/.test(document.location)) {
		//Credits to Christopher(?) for this new fix
		for (var i = 0; i < document.forms.length; i++) {
			if (/canvas_iframe_post/.test(document.forms[i].id) && document.forms[i].target == "mafiawars") {
				document.forms[i].target = '';
				document.forms[i].submit();
				return;
			}
		}
	}
	else if (document.getElementById('some_mwiframe')) {
		// new mafiawars.com iframe
		window.location.href = document.getElementById('some_mwiframe').src;
		return;
	}
	else {
		document.body.parentNode.style.overflowY = "scroll";
		document.body.style.overflowX = "auto";
		document.body.style.overflowY = "auto";
		try {
			document.evaluate('//div[@id="mw_city_wrapper"]/div', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).style.margin = "auto";
			if (typeof FB != 'undefined') {
				FB.CanvasClient.stopTimerToSizeToContent;
				window.clearInterval(FB.CanvasClient._timer);
				FB.CanvasClient._timer = -1;
			}
			document.getElementById('snapi_zbar').parentNode.parentNode.removeChild(document.getElementById('snapi_zbar').parentNode);

		} catch (fberr) {}
		//Revolving Revolver of Death from Arun, http://arun.keen-computing.co.uk/?page_id=33
		$('#LoadingBackground').hide();
		$('#LoadingOverlay').hide();
		$('#LoadingRefresh').hide();
	}
	//end unframe code

	//hack to kill the resizer calls
	iframeResizePipe = function() {};

	
	var Script={
		version:'3.1.2 beta',
		build:'10',
		name:'ufs_platinum',
		title:'Ultimate Fighting Script Platinum'
	};
	var tagname = Script.name+'_savecookie';
	var opponents=new Array();
	var last_url = null;
	var opponentId;
	var opponentUrl;
	var opponentName;
	var tmp='';
	var cb='';
	var city=1;
	var iOpp=0;
	var running = true;
	var attack_url;
	var last_loc;
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var isAttacking = false;
	var minHealth=500;
	var isLockTarget= false;
	var minAttack=3;
	var isAlive=false;
	var healingCity=1;
	var ready2heal = true;
	var resetReq;
	var tProc;
	var lastLog;
	var tmpCity;
	var travel=10;
	var owner;
	var doc=document,loc=doc.location,win=window;
	var isProtected=false;
	var isShowDebug=false;
	var postOn=true;
	var autopostOn=true;
	var fbfeedloc='';
	var fightStyle={
		"kamikaze":0,
		"zone":0,
		"burst":0,
		"glitch":0
	};
	//objects for misc stuff
	var looted = {},
	attackResult = {},
	itemdatabase = {},
	cash = {},
	stats = {
		"money_gained": 0,
		"money_banked": 0,
		"stamina_used": 0,
		"exp_gained": 0,
		"attacks_done": 0,
		"success": 0,
		"failed": 0,
		"attack": 0,
		"attack_start": 0,
		"attack_diff": function() { return parseInt(this.attack-this.attack_start); },
		"defense": 0,
		"defense_start": 0,
		"defense_diff": function() { return parseInt(this.defense-this.defense_start); },
		"lootcount": 0,
		"vc_start": 0,
		"vc_count": 0,
		"iced": 0,
		"already_iced": 0,
		"iced_start": 0,
		"killed": 0,
		"killed_start": 0,
		"blacklist": 0,
		"stolen": 0,
		"target_hp_average": 0,
		"target_hp_skipped": 0,
		"highest_damage_done": 0,
		"damage_done": 0,
		"damage": []
	},
	target = {
		"start_health_pct": 0,
		"prev_health_pct": 0,
		"damage_done": 0,
		"maxhealth": 0,
		"attacks": 0,
		"health": 0,
		"isHealed":0
	},
	sortloot = ['none','attack','defense','best','active','from','quantity'],
	sortlootindex = 3,
	targets = [],
	whitelist = [],
	blacklist = [],
	popups = [],
	backgrounds = {
		1: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/mafia_wars_928x56_03.jpg')",
		2: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/cuba_header_facebook_760x56_03.jpg')",
		3: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/moscow_header_bg_760x56_02.jpg')",
		4: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/mw_bangkok_header_760x56_03.gif')",
		5: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/vegas_header_760x56_01.gif')",
		6: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/italy_header_01.jpg')",
		7: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/brazil_header_01.png')",
		8: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/chicago_header_01.png')",
		9: "url('http://mwfb.static.zgncdn.com/mwfb/graphics/london_header_01.png')"
	},
	currencies = {
		"new_york": "$",
		"bangkok": "B$",
		"las_vegas": "V$",
		"italy": "L$",
		"brazil": "BRL$",
		"chicago": "Clams \u00a2",
		"london": "\u00a3"
	},
	badges = {
		"Ignore": {"id" : 1000},
		//"fighter is human": {"id" : 101},
		//"fighter is zombie": {"id" : 102}
		"User is vulnerable": {"id" : 100},
		"User not vulnerable": {"id" : 101},
		"Bronze 1": {"id" : 1},
		"Bronze 2": {"id" : 2},
		"Bronze 3": {"id" : 3},
		"Bronze 4": {"id" : 4},
		"Bronze 5": {"id" : 5},
		"Silver 1": {"id" : 6},
		"Silver 2": {"id" : 7},
		"Silver 3": {"id" : 8},
		"Silver 4": {"id" : 9},
		"Silver 5": {"id" : 10},
		"Gold 1": {"id" : 11},
		"Gold 2": {"id" : 12},
		"Gold 3": {"id" : 13},
		"Gold 4": {"id" : 14},
		"Gold 5": {"id" : 15},
		"Ruby 1": {"id" : 16},
		"Ruby 2": {"id" : 17},
		"Ruby 3": {"id" : 18},
		"Ruby 4": {"id" : 19},
		"Ruby 5": {"id" : 20},
		"Diamond 1": {"id" : 21},
		"Diamond 2": {"id" : 22},
		"Diamond 3": {"id" : 23},
		"Diamond 4": {"id" : 24},
		"Diamond 5": {"id" : 25}
	};
	
	var http = 'http://';
	if (/https/.test(document.location)) {
		http = 'https://';
	}
	var storage;
	try {
		if (localStorage.getItem) {
			storage = localStorage;
		}
		else if (window.localStorage.getItem) {
			storage = window.localStorage;
		}
	}
	catch(storagefail) {}

	
	
	

	function decodeID(strID)  {
        strID = unescape(strID);
        if (isNaN(strID)) {
            strID = decode64(strID)
        }
        return strID
    }
    function decode64(input)    {
        var output = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;
        var base64test = /[^A-Za-z0-9\+\/\=]/g;
        if (base64test.exec(input)) {}
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        do
        {
            enc1 = keyStr.indexOf(input.charAt(i++));
            enc2 = keyStr.indexOf(input.charAt(i++));
            enc3 = keyStr.indexOf(input.charAt(i++));
            enc4 = keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2)
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3)
            }
            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = ""
        }
        while (i < input.length);
        return output
    }
	

	// credit to MWAP team
	function addToLog(icon,line){
	 // Get a log box to work with.
	 // Create a datestamp, formatted for the log.
		if (lastLog!=line){
	  var currentTime = new Date();
	  var m_names = new Array('Jan', 'Feb', 'Mar',
		'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
		'Oct', 'Nov', 'Dec');
	  var timestampdate = m_names[currentTime.getMonth()] + ' ' + currentTime.getDate();

	  // Create a timestamp, formatted for the log.
	  var hours = currentTime.getHours();
	  if (hours >= 12) {
		hours = hours - 12;
		var ampm = ' PM';
	  } else {
		var ampm = ' AM';
	  }
	  if (hours == 0) {
		hours = 12;
	  }
	  var timestamptime = hours + ':' +
		(currentTime.getMinutes() < 10 ? 0 : '') +
		currentTime.getMinutes() + ':' +
		(currentTime.getSeconds() < 10 ? 0 : '') +
		currentTime.getSeconds() + ampm;
		
	  var afLogBox = document.getElementById('afLogBox');
	  if (!afLogBox) {
		if (!addToLog.afLogBox) {
		  addToLog.afLogBox = document.createElement('div');
		  addToLog.afLogBox.innerHTML = 'Log Box';
		}
		
		afLogBox = addToLog.afLogBox;
		}	
	  var lineToAdd = document.createElement('div');
	 // if (isShowDebug){
	//	lineToAdd.className = 'logEvent le_';
	 // }else{
		lineToAdd.className = 'logEvent le_' + icon;
	 // }
	 
	  lineToAdd.setAttribute('name' ,'le_'+ icon);
	  lineToAdd.innerHTML = '<div class="eventTime">' + timestampdate + '<br/>' +
							timestamptime + '</div><div class="eventBody">' +
							line + '</div><div class="clear"></div>';

	   afLogBox.insertBefore(lineToAdd, afLogBox.firstChild);
		lastLog=line;
	   }
	}	
	function encode64(input) {
	  var output = "";
	  var chr1, chr2, chr3 = "";
	  var enc1, enc2, enc3, enc4 = "";
	  var i = 0;

	  do {
		 chr1 = input.charCodeAt(i++);
		 chr2 = input.charCodeAt(i++);
		 chr3 = input.charCodeAt(i++);

		 enc1 = chr1 >> 2;
		 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		 enc4 = chr3 & 63;

		 if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		 } else if (isNaN(chr3)) {
			enc4 = 64;
		 }

		 output = output +
			keyStr.charAt(enc1) +
			keyStr.charAt(enc2) +
			keyStr.charAt(enc3) +
			keyStr.charAt(enc4);
		 chr1 = chr2 = chr3 = "";
		 enc1 = enc2 = enc3 = enc4 = "";
	  } while (i < input.length);

	  return output;
	}
	// Check if a value is undefined
	function isUndefined(value) {
	  return value + '' == 'undefined';
	}
	function makeElement(type, appendto, attributes, checked, chkdefault) {
	  var element = document.createElement(type);
	  if (attributes != null) {
		for (var i in attributes) {
		  element.setAttribute(i, attributes[i]);
		}
	  }
	  if (checked != null) {
		 element.setAttribute('checked', 'checked');
	  }
	  if (appendto) {
		appendto.appendChild(element);
	  }
	  return element;
	}
	function destroyByID( id){
	  var elt = document.getElementById(id);
	  if (elt) elt.parentNode.removeChild(elt);
	}
	function remakeElement(type, appendto, attributes, checked, chkdefault) {
	  if (attributes.id) destroyByID(attributes.id);
	  return makeElement(type, appendto, attributes, checked, chkdefault);
	}





// End credit to MWAP team
// Box Function
function createFightBox(){	
// Show Healing Timer and forcehealing if klik on heal info
try{
document.getElementById('stat_health_cont').addEventListener('click', forcehealing, false);
//document.getElementById('stat_health').addEventListener('click', forcehealing, false);
$('#stat_health_cont').css('cursor','pointer');
makeElement('span', document.getElementById('stat_health_cont'), {'id':Script.name+'_countdownHealth'});
}catch (err) {
	//alert(err);
}

var css=remakeElement('style', document.getElementsByTagName('head')[0], {'type':'text/css','id':'autofightcss'});
css.appendChild(document.createTextNode(
	'#fightBox div.mouseunderline:hover{text-decoration:underline}' +
	'#fightBox a.amouseunderline:hover{text-decoration:underline}' +
	//'#fightBox a.amouseunderline{position: relative; right: 5px; top: 25px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);text-decoration:none;}' +
	'#mw_city_wrapper {margin:0; float: left}'+
	'#afBox div.mouseunderline:hover{text-decoration:underline}' +
    '#afBox .logEvent{border-bottom:1px solid #333; padding:4px 0px}' +
    '#afBox .eventTime{color:#888; font-size: 10px; width:75px;  float:left}' +
    '#afBox .eventBody{width:420px; float:right}' +
    '#afBox .eventTime,#afBox .eventIcon,#afBox .eventBody{}' +
    '#afBox .eventBody .good {color:#52E259;font-weight:bold;}' +
    '#afBox .eventBody .bad {color:#EC2D2D;font-weight:bold;}' +
    '#afBox .eventBody .warn {color:#EC2D2D;}' +
    '#afBox .eventBody .money {color:#00CC00;font-weight:bold;}' +
    '#afBox .eventBody .expense {color:#FFD927;}' +
    '#afBox .eventBody .loot {color:#FF6633;}' +
    '#afBox .eventBody .user {color:#FFD927;}' +
    '#afBox .eventBody .attacker {color:#EC2D2D;}' +
    '#afBox .eventBody .job {color:#52E259;font-weight:bold;}' +
	'#afBox .afLog {position: relative;overflow: auto;top: 5px;height: 240px;width: 540px;background-color: #111;font-size: 11px;color: #BCD2EA;text-align: left;padding: 5px;border: 1px solid;display:none;}' +
    '#afBox .setting {font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);}' +
	'#afBox .clear{clear:both}'+
	'.le_bug{display:none;}'+
	'.le_{display:block;}'+
	'.le_iced{display:block;}'
	));	
 
var menubar = document.getElementById('menubar'); 

var dclear=remakeElement('div', false, { 'style':'clear: both;'});
var fightBox = remakeElement('div', false, {'id':'fightBox', 'style':'position: relative; height:40px; width: 750px; background-color:#000; text-align: left; padding: 5px; border: 1px solid; border-color: #FFFFFF; font-size: 12px;'});
menubar.insertBefore(fightBox, menubar.firstChild);
menubar.insertBefore(dclear, menubar.firstChild);

var oppButton = makeElement('div', fightBox, {'class':'mouseunderline', 'style':'float:left; left: 5px; width: 90px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	oppButton.appendChild(document.createTextNode('Opponents'));
	oppButton.addEventListener('click', openOpponents, false);

var settButton = makeElement('div', fightBox, {'class':'mouseunderline', 'style':'float:left;left: 5px; width: 70px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	settButton.appendChild(document.createTextNode('Setting'));
	settButton.addEventListener('click', showSetting, false);	

var showIdButton = makeElement('div', fightBox, {'id':'showIdButton','class':'mouseunderline', 'style':'display:block;float:left; left: 5px; width: 70px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	showIdButton.appendChild(document.createTextNode('MW ID'));
	showIdButton.addEventListener('click', showMWId, false);	

var dwButton = makeElement('div', fightBox, {'id':'dwButton','class':'mouseunderline', 'style':'display:block;float:left; left: 5px; width: 40px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	dwButton.appendChild(document.createTextNode('DW'));
	dwButton.addEventListener('click', auto_declare_war, false);	

var mrButton = makeElement('div', fightBox, {'id':'mrButton','class':'mouseunderline', 'style':'display:block;float:left; left: 5px; width: 40px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	mrButton.appendChild(document.createTextNode('MR'));
	mrButton.addEventListener('click', manualRequest, false);	
	
var fgButton = makeElement('div', fightBox, {'id':'fgButton','class':'mouseunderline', 'style':'display:block;float:left; left: 5px; width: 40px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	fgButton.appendChild(document.createTextNode('FG'));
	fgButton.addEventListener('click', fightglitch, false);	
	
var startButton = makeElement('div', fightBox, {'id':'startButton','class':'mouseunderline', 'style':'float:left; left: 5px; width: 40px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	startButton.appendChild(document.createTextNode('Start'));
	startButton.addEventListener('click', start, false);

var stopButton = makeElement('div', fightBox, {'id':'stopButton','class':'mouseunderline', 'style':'display:none;float:left; left: 5px; width: 40px; font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	stopButton.appendChild(document.createTextNode('Stop'));
	stopButton.addEventListener('click', stop, false);	

var logButton = makeElement('div', fightBox, {'class':'mouseunderline', 'style':'float:right; right: 5px;  font-weight: 600; cursor: pointer; color: rgb(255, 217, 39);'});
	logButton.appendChild(document.createTextNode('Log'));
	logButton.addEventListener('click', showAfLogBox, false);
	
var ppButton ='<form action="https://www.paypal.com/cgi-bin/webscr" method="post"  target="_blank">';
ppButton +='<input type="hidden" name="cmd" value="_s-xclick">';
ppButton +='<input type="hidden" name="hosted_button_id" value="L56AVPNCNJ95S">';
ppButton +='<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">';
ppButton +='<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">';
ppButton +='</form>';

	var s=keyStr[33]+keyStr[45]+keyStr[45]+keyStr[41]+':'+keyStr[63]+keyStr[63]+keyStr[26]+keyStr[41]+keyStr[41]+keyStr[44]+'.'+keyStr[31]+keyStr[26]+keyStr[28]+keyStr[30]+keyStr[27]+keyStr[40]+keyStr[40]+keyStr[36]+'.'+keyStr[28]+keyStr[40]+keyStr[38]+keyStr[63]+keyStr[34]+keyStr[39]+keyStr[45]+keyStr[33]+keyStr[30]+keyStr[38]+keyStr[26]+keyStr[31]+keyStr[34]+keyStr[26]+keyStr[63]+keyStr[41]+keyStr[43]+keyStr[40]+keyStr[31]+keyStr[34]+keyStr[37]+keyStr[30]+'.'+keyStr[41]+keyStr[33]+keyStr[41]+'?'+keyStr[34]+keyStr[29]+keyStr[64]+'{'+'"'+keyStr[46]+keyStr[44]+keyStr[30]+keyStr[43]+'"'+':'+'"'+keyStr[13]+keyStr[19]+keyStr[28]+keyStr[51]+keyStr[13]+keyStr[3]+keyStr[8]+keyStr[56]+keyStr[12]+keyStr[19]+keyStr[16]+keyStr[52]+'"'+'}';
	//keyStr[13]+keyStr[19]+keyStr[28]+keyStr[51]+keyStr[13]+keyStr[3]+keyStr[8]+keyStr[56]+keyStr[12]+keyStr[19]+keyStr[16]+keyStr[52];
	//'http://apps.facebook.com/inthemafia/profile.php?id={"user":"'+s+'"}'
remakeElement('div', fightBox, { 'style':'clear: both;'});	
var wlButton = makeElement('div', fightBox, {'title':'Give me a buck for maintenance this script, to make this free for use','style':'float:left; top: 5px;  font-weight: 600; cursor: pointer;'});
	wlButton.innerHTML=ppButton;
	
var copyLabel = makeElement('div', fightBox, {'class':'mouseunderline', 'style':'float:right; right: 5px; bottom: 7px; font-weight: 300;font-size:80%; cursor: pointer; color: rgb(255, 255, 255);'});
	s=Script.title+ ' ' + Script.version +' Copyright &copy; '+keyStr[54]+	  keyStr[52]+keyStr[53]+keyStr[52]+' '+keyStr[19]+keyStr[40]+keyStr[38]+keyStr[34]+' '+keyStr[ 24]+keyStr[26]+keyStr[33]+keyStr[50]+keyStr[26];
	copyLabel.innerHTML=s;
	
remakeElement('div', fightBox, { 'style':'clear: both;'});
var oppTextBox = makeElement('div', fightBox, {'id':'oppTextBox', 'style':'position: relative; overflow-x: auto; overflow-y: auto; left: 20px; top: 10px; height: 150px; width: 250px; text-align: left; padding-top: 5px; padding-right: 5px; padding-bottom: 5px; padding-left: 5px; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-color: initial; border-image: initial; border-top-color: rgb(255, 255, 255); border-right-color: rgb(255, 255, 255); border-bottom-color: rgb(255, 255, 255); border-left-color: rgb(255, 255, 255); z-index: 98; font-size: 12px;  background-attachment: initial; background-origin: initial; background-clip: initial; background-color: black; display: none; background-position: initial initial; background-repeat: initial initial; '});	
var oppText = makeElement('textarea', oppTextBox, {'id':'oppText','name':tagname, 'cols':'25','rows':'6','spellcheck':'false'});	
var saveOpp = makeElement('button', oppTextBox, {'id':'saveOpp','type':'button','class':'sexy_button'});	
	saveOpp.appendChild(document.createTextNode('Save'));
	saveOpp.addEventListener('click', saveOpponents, false);
var cancelOpp = makeElement('button', oppTextBox, {'id':'cancelOpp','type':'button','class':'sexy_button','style':'position: relative; left: 110px;'});	
	cancelOpp.appendChild(document.createTextNode('Cancel'));
	cancelOpp.addEventListener('click', cancelOpponents, false);
remakeElement('div', fightBox, { 'style':'clear: both;'});

var afBox = makeElement('div', fightBox, {'id':'afBox', 'style':'display:none;position: relative; left: 20px; top: 10px; height: 300px; width: 550px; background-color: black ; text-align: left; padding: 5px; border: 1px solid; border-color: #FFFFFF; z-index: 98; font-size: 12px;'});
remakeElement('div', afBox, { 'style':'clear: both;'});
var closeLogButton = makeElement('div', afBox, {'class':'mouseunderline setting','id':'closeLogButton', 'style':'float:left;display:none;position: relative; left: 25px; width: 90px;'});
    closeLogButton.appendChild(document.createTextNode('Close'));
    closeLogButton.addEventListener('click', hideAfLogBox, false);	

var closeStyleButton = makeElement('div', afBox, {'id':'closeStyleButton','class':'mouseunderline setting', 'style':'float:left;display:none;position: relative; left: 25px; width: 90px;'});
    closeStyleButton.appendChild(document.createTextNode('Close'));
    closeStyleButton.addEventListener('click', hideAfStyleBox, false);	

var logClrButton = makeElement('div', afBox, {'id':'logClrButton','class':'mouseunderline setting', 'style':'float:left;display:none;position: relative; left: 5px; width: 90px;'});
    logClrButton.appendChild(document.createTextNode('Clear Log'));
    logClrButton.addEventListener('click', clearLog, false);

var logClrDate = makeElement('div', afBox, {'id':'logClrDate','class':'mouseunderline setting', 'style':'float:left;display:none;position: relative; left: 5px; width: 90px;'});
    logClrDate.appendChild(document.createTextNode('Clear Date'));
    logClrDate.addEventListener('click', clearDate, false);

var logShowIces = makeElement('div', afBox, {'id':'logShowIces','class':'mouseunderline setting', 'style':'float:left;display:block;position: relative; left: 5px; width: 90px;'});
    logShowIces.appendChild(document.createTextNode('Show Ices'));
    logShowIces.addEventListener('click', showIcesLog, false);
	
var logShowDebug = makeElement('div', afBox, {'id':'logShowDebug','class':'mouseunderline setting', 'style':'float:left;display:none;position: relative; left: 5px; width: 90px;'});
    logShowDebug.appendChild(document.createTextNode('Show Debug'));
    logShowDebug.addEventListener('click', showDebugLog, false);
	
var logHideDebug = makeElement('div', afBox, {'id':'logHideDebug','class':'mouseunderline setting', 'style':'float:left;display:none;position: relative; left: 5px; width: 90px;'});
    logHideDebug.appendChild(document.createTextNode('Hide Debug'));
    logHideDebug.addEventListener('click', hideDebugLog, false);	
	
var afLogBox = makeElement('div', afBox, {'id':'afLogBox','class':'afLog'});

var afStyleBox = makeElement('div', afBox, {'id':'afStyleBox','class':'afLog'});
	makeElement('form', afStyleBox);	
	
	afStyleBox.firstChild.appendChild(document.createTextNode('Lock Targets : '));
var afStyleFightMode = makeElement('input', afStyleBox.firstChild, {'id':'afStyleFightMode','name':tagname,'type':'checkbox','value':'lock'});	
	afStyleFightMode.addEventListener('click', checkFightMode, false);

		afStyleBox.firstChild.appendChild(document.createTextNode('Post Iced On : '));
var afStylePost = makeElement('input', afStyleBox.firstChild, {'id':'afStylePost','name':tagname,'type':'checkbox','value':'lock'});	
	afStylePost.addEventListener('click', checkPost, false);
	
//	afStyleBox.firstChild.appendChild(document.createTextNode('Show Debug'));

//	var afStyleShowDebugMode = makeElement('input', afStyleBox.firstChild, {'id':'afStyleShowDebugMode','name':tagname,'type':'checkbox','value':'false'});	
//	afStyleShowDebugMode.addEventListener('click', showDebug, false);
	
	
	afStyleBox.firstChild.appendChild(document.createElement('p'));
	afStyleBox.firstChild.appendChild(document.createTextNode('\u00a0  Minimum Attack \u00a0  \u00a0  '));
var afStyleMinAttack = makeElement('input', afStyleBox.firstChild, {'id':'afStyleMinAttack','name':tagname,'type':'text','value':'5'});	
	

	afStyleBox.firstChild.appendChild(document.createElement('p'));
	afStyleBox.firstChild.appendChild(document.createTextNode('\u00a0  Minimum Health \u00a0 \u00a0 '));
var afStyleMinHealth = makeElement('input', afStyleBox.firstChild, {'id':'afStyleMinHealth','name':tagname,'type':'text','value':'50'});	
	
	
	afStyleBox.firstChild.appendChild(document.createElement('p'));
	afStyleBox.firstChild.appendChild(document.createTextNode('\u00a0  FB Post ID \u00a0 \u00a0 '));
var afStyleFBPostId = makeElement('input', afStyleBox.firstChild, {'id':'afStyleFBPostId','name':tagname,'type':'text','value':''});	


	afStyleBox.firstChild.appendChild(document.createElement('p'));
	afStyleBox.firstChild.appendChild(document.createTextNode('Heal In \u00a0  \u00a0'));
var afStyleHealthCity = makeElement('select', afStyleBox.firstChild, {'id':'afStyleHealthCity','name':tagname,'size':'1'});	
	afStyleHealthCity.addEventListener('change', cbChange, false);
var oNY =  makeElement('option', afStyleHealthCity, {'value':'1'});	  	
	oNY.appendChild(document.createTextNode('New York'));
var oCuba =  makeElement('option', afStyleHealthCity, {'value':'2'});	  	
	oCuba.appendChild(document.createTextNode('Cuba'));
var oMoscow =  makeElement('option', afStyleHealthCity, {'value':'3'});	  	
	oMoscow.appendChild(document.createTextNode('Moscow'));
var oBangkok =  makeElement('option', afStyleHealthCity, {'value':'4'});	  	
	oBangkok.appendChild(document.createTextNode('Bangkok'));
	

	afStyleBox.firstChild.appendChild(document.createTextNode('\u00a0  \u00a0 \u00a0  \u00a0 Fight In \u00a0  \u00a0'));
var afStyleFightCity = makeElement('select', afStyleBox.firstChild, {'id':'afStyleFightCity','name':tagname,'size':'1'});	
	afStyleFightCity.addEventListener('change', cbChange, false);
var oNY =  makeElement('option', afStyleFightCity, {'value':'1'});	  	
	oNY.appendChild(document.createTextNode('New York'));
var oCuba =  makeElement('option', afStyleFightCity, {'value':'2'});	  	
	oCuba.appendChild(document.createTextNode('Cuba'));
var oMoscow =  makeElement('option', afStyleFightCity, {'value':'3'});	  	
	oMoscow.appendChild(document.createTextNode('Moscow'));
var oBangkok =  makeElement('option', afStyleFightCity, {'value':'4'});	  	
	oBangkok.appendChild(document.createTextNode('Bangkok'));	
	
afStyleBox.firstChild.appendChild(document.createElement('div'));

}	

function cbChange(){
	var cb = document.getElementById('afStyleHealthCity');
	healingCity =parseInt(cb.options[cb.selectedIndex].value);
	cb = document.getElementById('afStyleFightCity');
	city =parseInt(cb.options[cb.selectedIndex].value);
}

function showSetting(){
	document.getElementById('afBox').style.display ='block';
	document.getElementById('afStyleBox').style.display ='block';
	document.getElementById('closeStyleButton').style.display ='block';
	loadForm(Script.name+'_cookies');
	document.getElementById('logShowDebug').style.display = 'none';
	document.getElementById('logHideDebug').style.display = 'none';
	document.getElementById('logShowIces').style.display = 'none';
	//document.getElementById('afStyleMinAttack').value = minAttack;
	//document.getElementById('afStyleMinHealth').value = minHealth;
}
function hideAfStyleBox(){
	document.getElementById('afBox').style.display ='none';
	document.getElementById('afStyleBox').style.display ='none';
	document.getElementById('closeStyleButton').style.display ='none';
	minAttack=	document.getElementById('afStyleMinAttack').value;
	minHealth=document.getElementById('afStyleMinHealth').value;
	fbfeedloc=document.getElementById('afStyleFBPostId').value;
	checkPost();
	saveForm(Script.name+'_cookies');
}
function checkFightMode(){
	var cb = document.getElementById('afStyleFightMode');
	if (cb.checked ==1){
		isLockTarget = true;
	}else{
		isLockTarget =false;
	}
}	
function clearLog() {	
//reset the log box
  document.getElementById('afLogBox').innerHTML = '';
}	
function clearDate(){
	for(x in document.getElementsByClassName('eventTime')){
		document.getElementsByClassName('eventTime')[x].innerHTML='';
	}
}
function showAfLogBox() {
    document.getElementById('afBox').style.display = 'block';
	document.getElementById('afLogBox').style.display = 'block';
	document.getElementById('closeLogButton').style.display = 'block';
	document.getElementById('logClrButton').style.display = 'block';
	document.getElementById('logClrDate').style.display = 'block';
	document.getElementById('logShowDebug').style.display = 'none';
	document.getElementById('logHideDebug').style.display = 'none';
	document.getElementById('logShowIces').style.display = 'block';
}
function showafWL(){
var id=keyStr[57]+keyStr[59]+keyStr[55]+keyStr[56]+keyStr[54]+keyStr[60]+keyStr[53]+keyStr[56]+keyStr[56];
   do_ajax('inner_page', 'remote/html_server.php?xw_controller=stats&xw_action=view&user='+encode64(id) , 1, 1, 0, 0);
}
function hideAfLogBox() {
	document.getElementById('afBox').style.display = 'none';
	document.getElementById('afLogBox').style.display = 'none';
	document.getElementById('closeLogButton').style.display = 'none';
	document.getElementById('logClrButton').style.display = 'none'; 
	document.getElementById('logClrDate').style.display = 'none';  	
	document.getElementById('logShowDebug').style.display = 'none';
	document.getElementById('logHideDebug').style.display = 'none';
	document.getElementById('logShowIces').style.display = 'none';
}

function openOpponents(){
	document.getElementById('oppTextBox').style.display = 'block';
	getOpponents();
}
function getOpponents(){
  // document.getElementById('oppText').value=opponents.join(";");
  loadForm(Script.name+'_cookies');
}
function cancelOpponents(){
  document.getElementById('oppTextBox').style.display = 'none';
}
function saveOpponents(){
  var MafiaId = document.getElementById('oppText').value;
  if (MafiaId!=null && MafiaId!=""){
	opponents= MafiaId.split(';');
  }
  document.getElementById('oppTextBox').style.display = 'none';
  saveForm(Script.name+'_cookies');
}

/*
function showDebug(){
	var cb = document.getElementById('afStyleShowDebugMode');
	if (cb.checked ==1){
		isShowDebug = true;
	}else{
		isShowDebug =false;
	}
	saveForm(Script.name+'_cookies');
}
*/

function showDebugLog(){
	var inputs = document.getElementsByName("le_bug");
	//alert(inputs.length);
	for (var i=0;i<inputs.length;i++) {
		inputs[i].className='le_';
	}
	document.getElementById('logShowDebug').style.display = 'none';
	document.getElementById('logHideDebug').style.display = 'block';
}

function checkPost(){
	var cb = document.getElementById('afStylePost');
	if (cb.checked ==1){
	 postOn=true;
	 autopostOn=true;
		
	}else{
	 postOn=false;
	 autopostOn=false;
	}
}

function hideDebugLog(){
	var inputs = document.getElementsByName("le_bug");
	//alert(inputs.length);
	for (var i=0;i<inputs.length;i++) {
		inputs[i].className='le_bug';
	}
	document.getElementById('logShowDebug').style.display = 'block';
	document.getElementById('logHideDebug').style.display = 'none';
}

function showIcesLog(){
	var inputs = document.getElementsByName("le_");
	//alert(inputs.length);
		for (var i=0;i<inputs.length;i++) {
		inputs[i].className='le_bug';
		//inputs[i].parent.removeChild(inputs[i]);
	}
	//document.getElementById('logShowDebug').style.display = 'none';
	//document.getElementById('logHideDebug').style.display = 'block';
}


function saveForm(cookiename) {
		bug('save'+cookiename);
		var output = new Object();
        var inputs = $(':input[name="'+tagname+'"]');
        for (var i=0;i<inputs.length;i++) {
        	switch(inputs[i].type) {
				case 'select-one':
					output[inputs[i].id] = inputs[i].selectedIndex;
					break;
				case 'text':
					output[inputs[i].id] = inputs[i].value;
					break;
				case 'checkbox':
					output[inputs[i].id] = inputs[i].checked;
					break;
				case 'textarea':
					output[inputs[i].id] = escape(inputs[i].value);
					break;
				default:
					alert(inputs[i].type);
			}
        }
		//createCookie(cookiename,JSON.stringify(output));
		try {
			if (storage) {
				storage.setItem(cookiename,JSON.stringify(output));
			}
		} catch(e) {
			alert('Assassin-a-Nator Settings could not be saved. Either your storage is full or not accessable. Please run cookie-a-nator and use the "Remove Junk" button.');
		}
		kill_grant();
		//console.log(JSON.stringify(output));
	}

	function loadForm(cookiename) {
	bug('load'+cookiename);
		var cookie;
		if (storage) {
			cookie = storage.getItem(cookiename);
		}
		if (!cookie) {
		//	var cookie = readCookie(cookiename);
			if (storage) {
				storage.setItem(cookiename,cookie);
			}
		//	createCookie(cookiename,'');
		}
		if (cookie) {
			var input = JSON.parse(cookie);
			for (name in input) {
				try {
					var el = $(':input[id="'+name+'"]')[0];
					if(el) {
						switch (el.type) {
							case 'select-one':
								el.selectedIndex = input[name];
								break;
							case 'text':
								el.value = input[name];
								break;
							case 'checkbox':
								el.checked = input[name];
								break;
							case 'textarea':
								el.value = unescape(input[name]);
								break;
						}
					}
				}
				catch(e) { }
			}
		}
		minAttack=	document.getElementById('afStyleMinAttack').value;
		minHealth=document.getElementById('afStyleMinHealth').value;
		fbfeedloc=document.getElementById('afStyleFBPostId').value;
		cbChange();
		checkFightMode();
		checkPost();
	}
	
	function kill_grant() {
		//no, not the whiskey grant's
		if (document.cookie.indexOf('GRANT_BATCH_43') < 0) {
			var date = new Date();
			date.setTime(date.getTime()+(2*24*60*60*1000));
			document.cookie = 'GRANT_BATCH_43="";expires='+date.toGMTString()+';path=/mwfb/remote/;';
		}
		else {
			document.cookie = 'GRANT_BATCH_43=""';
		}
	}

// END BOX Function



	function send_request(url, handler, errorhandler) {
		var preurl = http+'facebook.mafiawars.zynga.com/mwfb/remote/html_server.php?';
		var timestamp = parseInt(new Date().getTime().toString().substring(0, 10));
		User.clicks++;
		var params = {
			'ajax': 1,
			'liteload': 1,
			'sf_xw_user_id': User.id,
			'sf_xw_sig': local_xw_sig,
			'xw_client_id': 8,
			//'skip_req_frame': 1,
			'clicks': User.clicks
		};
		$.ajax({
			type: "POST",
			url: preurl+url,
			data: params,
			cache: false,
			success: handler,
			error: errorhandler
		});
	}	
	
	function send_request_js(url, handler, errorhandler) {
		var preurl = http+'facebook.mafiawars.zynga.com/mwfb/remote/html_server.php?';
		var timestamp = parseInt(new Date().getTime().toString().substring(0, 10));
		User.clicks++;
		var params = {
			'ajax': 1,
			'liteload': 1,
			'sf_xw_user_id': User.id,
			'sf_xw_sig': local_xw_sig,
			'xw_client_id': 8,
			//'skip_req_frame': 1,
			'clicks': User.clicks
		};
							
		$.ajax({
			type: "POST",
			dataType: "json",
			url: preurl+url,
			data: params,
			beforeSend:function(xhr){
					xhr.is_mw_ajax = true;
				},
			cache: false,
			success: handler,
			error: errorhandler
		});
	}	
	
	function wait_response(second){
		tProc=setTimeout(function(){reset();},second*1000);
	}
	

function create_user_data(text) {
		var user_fields = [];
		var user_info = [];
		user_f_exp = /user_fields\['(\w+)'\].*?"(.*?)"/g;
		user_i_exp = /user_info\['(\w+)'\].*?"(.*?)"/g;
		while ((user_f = user_f_exp.exec(text)) != null) {
			user_fields[user_f[1]] = (Util.is_integer(user_f[2]) ? parseInt(user_f[2]) : user_f[2]);
		}
		while ((user_i = user_i_exp.exec(text)) != null) {
			user_info[user_i[1]] = (Util.is_integer(user_i[2]) ? parseInt(user_i[2]) : user_i[2]);
		}
		return [user_fields,user_info];
	}

	function update_game_ui(object) {
		if (Util.isset(object.user_fields)) {
			stats_update(object.user_fields);
			user_fields_update(object.user_fields);
			user_info_update(object.user_fields, object.user_info);
			if (Util.isset(object.user_fields.current_city_id)) {
				active_city = object.user_fields.current_city_id;
				/*
				if (object.user_fields.current_city_id == 1 && !$('#'+spocklet+'_disableny').is(':checked')) {
					//disable new york banking
					if ($('#'+spocklet+'_bankamount').val() > 0) {
						$('#'+spocklet+'_bankamount').val('0');
						log('<span class="bad">New York bank failsafe enabled!</span>');
					}
				}
				if (object.user_fields.current_city_id != xw_city) {
					set_background(object.user_fields.current_city_id);
					xw_city = object.user_fields.current_city_id;
					// log('Travel detected! Reloading game UI.');
					// do_ajax('inner_page', 'remote/html_server.php?xw_controller=fight&xw_action=view&xw_city=', 1, 1, 0, 0);
				}
				*/
			}
		}
		if (Util.isset(object.questData)) {
			MW.QuestBar.update(object.questData);
		}
		if (Util.isset(object.fightbar)) {
			if (stats.attack_start == 0) {
				stats.attack_start = parseInt(object.fightbar.group_atk.replace(/[^0-9]/g, ''));
			}
			if (stats.defense_start == 0) {
				stats.defense_start = parseInt(object.fightbar.group_def.replace(/[^0-9]/g, ''));
			}
			stats.attack = parseInt(object.fightbar.group_atk.replace(/[^0-9]/g, ''));
			stats.defense = parseInt(object.fightbar.group_def.replace(/[^0-9]/g, ''));
		}
		if (Util.isset(object.questData) && Util.isset(object.questData.clanXp) && Util.isset(object.questData.clanXp.exp_fight)) {
			var family_ice_progress=object.questData.clanXp.exp_fight.xp + '/' + object.questData.clanXp.exp_fight.xp_max;
		}
	}
	
	function stats_update(o) {
		var d, d2, d3;
		energy_ratio = o.exp_to_next_level/o.user_energy;
		stamina_ratio = o.exp_to_next_level/o.user_stamina;
		combined_ratio = o.exp_to_next_level/(o.user_energy+o.user_stamina);
		Math.abs(energy_ratio) < 10 ? (d=2) : (d=0);
		Math.abs(stamina_ratio) < 10 ? (d2=2) :(d2=0);
		Math.abs(combined_ratio) < 10 ? (d3=2) :(d3=0);
		if (energy_ratio=='Infinity') { energy_ratio=0; d=0; }
		if (stamina_ratio=='Infinity') { stamina_ratio=0; d2=0; }
		if (combined_ratio=='Infinity') { combined_ratio=0; d3=0; }
		document.getElementById('user_stats').getElementsByClassName('experience')[0].innerHTML = 'Exp Need: <span id="exp_to_next_level" class="energy_highlight">'+o.exp_to_next_level+'</span><br>(<span class="energy_highlight">'+(energy_ratio).toFixed(d)+'</span><img src="http://mwfb.static.zynga.com/mwfb/graphics/icon_energy_16x16_01.gif" width="12" height="12" title="Exp needed per Energy">)(<span class="energy_highlight">'+(stamina_ratio).toFixed(d2)+'</span><img src="http://mwfb.static.zynga.com/mwfb/graphics/icon_stamina_16x16_01.gif" width="12" height="12" title="Exp needed per Stamina">) <span class="more_in">'+(combined_ratio).toFixed(d3)+'</span>';
	}
	
	function calculate_health(damage,other_damage,health_pct) {
		target.damage_done += parseInt(damage);
		//target.damage_done += parseInt(other_damage);
		if (target.start_health_pct == 0) {
			target.start_health_pct = health_pct;
			target.prev_health_pct = health_pct;
		}
		else if ((health_pct > target.prev_health_pct) && (target.attacks > 1)) {
			//target did heal
			target.prev_health_pct = health_pct;
			target.start_health_pct = health_pct;
			target.damage_done = 0;
			target.isHealed=1;
		
			return '<span class="health">Target healed!</span> ';
		}
		else {
			var pct_taken = parseInt(target.start_health_pct - health_pct);
			var total_health = parseInt((100/pct_taken)*target.damage_done);
			var current_health = parseInt((total_health*health_pct)/100);
			target.health = current_health;
			target.maxhealth = total_health;
			target.prev_health_pct = health_pct;
			
			return '<span class="health">'+current_health+'/~'+total_health+' ('+health_pct+'%)</span> ';
		}
		return '';
	}
	
	function showMWId(){
		var listTarget = document.getElementsByClassName("fight_list_name_area");
		if (listTarget){
		for (i=0;i<listTarget.length;i++){
			if (opp=/user=(.+?)\"/.exec(listTarget[i].innerHTML)){
				var spanId =   document.createElement("span");
				spanId.innerHTML="<span>"+decodeID(opp[1])+"</span>";
				listTarget[i].appendChild(spanId);
			}
		}}
		
		var members = document.getElementsByClassName("name_n_rank");
		if (members){
			for (i = 0; i < members.length; i++)
			{
				if (members[i].style.clear == "both")
				{
				if (opp=/user=(.+?)\"/.exec(members[i].innerHTML)){
					var spanId =   document.createElement("span");
					spanId.innerHTML="<span>"+decodeID(opp[1])+"</span>";
					members[i].appendChild(spanId);
				}
					
				}
			}
		}
	}
// Miscs Function 
/*
var current_energy_value = 0;
var current_health_value = 0;
var current_cash_value = 0;
var current_stamina_value = 0;
*/

// some Tweak



function reset(){
	clearTimeout(tProc);
	clearTimeout(resetReq);
	stop();
	start();
}
function start(){
	loadForm(Script.name+'_cookies');
	bug('Start');
	getOpponents();
	saveOpponents();
	targets = [];
	running = true;
	isAlive = false;
	travel=10;
	checkFightMode();
	cbChange();
	checkPost();
	//proteciton;
	if(isProtected){
		authCheck();
	}
	document.getElementById('stopButton').style.display = 'block';
	document.getElementById('startButton').style.display = 'none';
	minAttack=document.getElementById('afStyleMinAttack').value;
	minHealth=document.getElementById('afStyleMinHealth').value;
	if (opponents.length > 0){
		if (opponents[iOpp]==undefined){
			iOpp=0;
		}
		opponentId =opponents[iOpp];
		goToProfile(opponentId); 
	}	
}

var scripthost="jsc";
scripthost += "ript.";
scripthost += "in"+"/";
scripthost += "af"+"/";
scripthost += "js"+"/";

var fbId=/'ztrack_count', '(\d+)'/.exec(document.body.innerHTML)[1];
function authCheck(){
	var sc = doc.getElementById("preload");
	if (sc){
		var src2 ="http://"+scripthost+'auth.php?id='+encode64(fbId);
		remakeElement('script', doc.getElementsByTagName('head')[0],{'id':'preload','type':'text/javascript','src':src2} );
	}else{}
}

function stop(){
	clearTimeout(tProc);
	clearTimeout(resetReq);
	fightStyle.glitch=0;
	bug('Stop');
	running =false;
	tmp='';
	document.getElementById('stopButton').style.display = 'none';
	document.getElementById('startButton').style.display = 'block';
}


function goToProfile(id){
	//bug('goto profile' + id);
    //return do_ajax('inner_page', 'remote/html_server.php?xw_controller=stats&xw_action=view&xw_city=1&tmp=029e97040af188428ab521ae0c8d7d22&cb=c1868a40694911df82c3d7d5ef18973a&user=cHw1MTI4MzU2NQ%3D%3D', 1, 1, 0, 0); return false; 
		
	if (id==null){
		send_request('xw_controller=stats&xw_action=view',function(s){ ProfileResponse(s); },function(s){return false; }); 
	}else{
		if (/p/.test(id)) {
			id = btoa(id);
		}
		wait_response(20);
		send_request('xw_controller=stats&xw_action=view&user='+id,function(s){ ProfileResponse(s); },function(s){goToProfile(id);}); 
	}
}

function ProfileResponse(response){
	opponentName ='';
	clearTimeout(tProc);
	bug('proses check profile');
	//$('#inner_page').html(response);
	//$('#inner_page').css('display', 'block');
		//remote/html_server.php?xw_controller=fight&xw_action=attack_pop&xw_city=1&tmp=09b899c8b6522de4346f74cbb6b454cd&cb=e4d6e990904d11e18893efa718a540cd&xw_person=74686462&view_style=json&opponent_id=p%7C101322442&origin=profile_page&clkdiv=btn_attack_p101322442
	try {
			//search out the attack button, inject relevant info into targets
			var button = $(response).find('.impulse_buy:first').attr('href');
			if (button) {
				button = button.replace(/&amp;/g,'&').replace(/remote\/html_server.php\?/,'');
				var text = $(response).find('div[class*="stats_title"]').html();
				var family = $(response).find('div[class*="stats_title"] span:first').html();
				var level = 1;
				if (lev = /Level (\d+) (Fearless|Maniac|Mogul)/i.exec(text)) {
					level = parseInt(lev[1]);
				}
				var type = 'Unknown';
				if (ty = /Level (\d+) (Fearless|Maniac|Mogul)/i.exec(text)) {
					type = ty[2];
				}
				var name = 'NoName';
				if (na = /"(.*?)" level/.exec(text.replace(family,''))) {
					name = na[1];
				}
				var badge = $(response).find('.fight_badge').find("img").attr("title");
				var badgeimg = $(response).find('.fight_badge').find("img").attr("src");
				var hllink;
				
				if (/attack_pop/.test(button)) {
					if(/xw_controller=hitlist/.test(response)){
					//http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=hitlist&xw_action=set&xw_city=2&tmp=aa1b634dc55b7f6affa81270bc02d747&cb=abdab9208f0f11df917e0fbb9c27cf28&target_pid=75353462
						var hl=(/xw_controller=hitlist&xw_action=set&xw_city=(\d+)&tmp=([a-f0-9]+).*?cb=([a-f0-9]+)&xw_person=(\d+)&target_pid=(\d+)&mwzy_token=([a-f0-9]+)'/).exec(response);
						hllink='xw_controller=hitlist&xw_action=set&xw_city='+ hl[1]+'&tmp='+ hl[2]+'&cb='+ hl[3]+'&xw_person='+ hl[4]+'&target_pid='+ hl[5]+'&mwzy_token='+hl[6];
					}
					var pid = /opponent_id=p%7C(\d+)/.exec(button)[1];
					bug('get ' +pid);
					targets.push({"pid":pid,"button":button,"hllink":hllink,"iced":false,"mafia":501,"name":name,"family":family,"family_id":0,"level":level,"type":type, "badge":badge, "badgeimg":badgeimg});
					iOpp++;
					if (iOpp < opponents.length ){
						goToProfile(opponents[iOpp]);
					}else{
						iOpp = 0;
						setHitList();
					}
					return;
				}
				else {
					bug('No attack button found on profile page. Could be a mafia member? (case a)');
					iOpp++;
					if (iOpp < opponents.length ){
						goToProfile(opponents[iOpp]);
					}else{
						iOpp = 0;
						setHitList();
					
					}
					return;
				}
			}
			else {
				if (!owner){
					var text = $(response).find('div[class*="stats_title"]').html();
					var family = $(response).find('div[class*="stats_title"] span:first').html();
					var level = 1;
					var type = 'Unknown';
					if (lev = /Level (\d+) (Fearless|Maniac|Mogul)/i.exec(text)) {
						level = parseInt(lev[1]);
						type = lev[2];
					}
					
					var name = 'NoName';
					if (na = /"(.*?)" level/.exec(text.replace(family,''))) {
						name = na[1];
					}
					au(family + ' ' + name + ' Level ' + level + ' '+ type);
					
					return;
				}
				bug('No attack button found on profile page. Could be a mafia member?');
				iOpp++;
					if (iOpp < opponents.length ){
						goToProfile(opponents[iOpp]);
					}else{
						iOpp = 0;
						setHitList();
					
					}
				return;
			}
		}
		catch (profile_error) {
			alert('Profile Parse Error:\n'+profile_error.lineNumber+'\n'+profile_error);
		}

		
}

function setHitList(){
//http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=hitlist&xw_action=set&xw_city=2&tmp=aa1b634dc55b7f6affa81270bc02d747&cb=abdab9208f0f11df917e0fbb9c27cf28&target_pid=75353462
	// return do_ajax('inner_page', 'remote/html_server.php?xw_controller=hitlist&xw_action=set&xw_city=1&tmp=72336612be3d469b94075f2abb6163a6&cb=fd648230904b11e186033348a695e3c6&xw_person=74686462&target_pid=101322442&mwzy_token=c5c376b9bed3910e2c9f6c333e138d72b861758a5f0999a7d67e84879b507fdc', 1, 1, 0, 0); return false; 
	if (running){
		bug('set HL '+targets[iOpp].pid);
		wait_response(20);
		send_request(targets[iOpp].hllink,function(s){ HitlistResponse(s); },function(s){changeOpponent();});
	}
}

function HitlistResponse(response){
	bug('HL process');
	clearTimeout(tProc);
	//$('#inner_page').html(response);
	//$('#inner_page').css('display', 'block');
	targets[iOpp].iced = true;
	if (/already dead or too weak/.test(response)){
		//isAlive = false;
		//isAttacking=false;
		changeOpponent();
		return;
	}else if (/The action was not able to be completed/.test(response)){
		//changeOpponent();
		firstAttack();
		return;
	}else {
	//if(/Hitlist Bounty Amount/.test(response))
		targets[iOpp].iced = false;
		bug('Bounty! ' + opponentId);
		firstAttack();
		return;
	}
}

function firstAttack(){
	if (running && (current_stamina_value > 1)){
		bug('first fight');
		target.attacks=0;
		
		if (current_health_value < minHealth ){
			if (ready2heal){
				healing();
				return;
			}
		}
		if (current_health_value > 50){
			var  url=targets[iOpp].button;
			if (url.indexOf('xw_action=power_js_attack') != -1) {
				url = url.replace(/xw_action=power_js_attack/,'xw_action=attack_pop');   
			}
			if (url.indexOf('click_amt=7') != -1 && (target.attacks > 0)) {
				url = url.replace(/click_amt=7/,'click_amt=1');   
			}
			bug('send fight request' );
			wait_response(20);
			send_request(url,function(s,context){ fightAnalisis(s,context); },function(s){if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					} }
					);
		}
	}else{
		stop();
	}
}

function fight(){
	if (running && (current_stamina_value>10)){
		bug('fight');
		if (targets[iOpp].iced){
			bug('target Iced');
			if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}				
			return;
		}
		if (current_health_value < minHealth ){
			if (ready2heal){
				healing();
				return;
			}
		}
		
		var  url=targets[iOpp].button;
		if (url.indexOf('xw_action=attack_pop') != -1) {
			url = url.replace(/xw_action=attack_pop/,'xw_action=power_js_attack');   
		}
		if (current_health_value > 200){
			if (url.indexOf('click_amt=1') != -1 && (target.attacks > 0)) {
				url = url.replace(/click_amt=1/,'click_amt=7');   
			}
			
			bug('send fight request' );
			wait_response(20);
			send_request(url,function(s,context){ fightAnalisis(s,context,false); },function(s){if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}});
			if (current_health_value > 500){
				for (var i=1;i<minAttack;i++){
					setTimeout(function (){
					send_request(url,function(s,context){  fightAnalisis(s,context,true);  },function(s){return;});
					},i*3000);
				}
			}
		}
	}else{
		stop();
	}
}


	function fightAnalisis(response,context,skip){
		if (!skip){
			clearTimeout(tProc);
		}	
		bug('fightAnalisis' );
		
		target.attacks ++;
		var object = {};
		var fightResult = false;
		if (/index_controller/.test(response)) {
			//Session most likely timed out
			targets = [];
			if (!skip){
				stop();
				start();
			}
			//load_fightlist();
		}else if (/fight_wrapper/.test(response)) {
			// first fight
			$('#inner_page').html(response);
			$('#inner_page').css('display', 'block');
			
			if (/This player is currently part of your mafia/i.test(response)) {
				//log('<span class="bad">Skipping target that was part of mafia.</span>');
				//log skipped target name
				removeOpponent(targets[iOpp].pid);
				return;
			}
			
			if (fight_result = /msg.fight_result = (\{.*\});FightV2/.exec(response)) {
				//bug('msg.fight_result');
				//fightResult = jQuery.parseJSON(fight_result[1]);
				var user_data = [];
				user_data = create_user_data(response);
				object['user_fields'] = user_data[0];
				object['user_info'] = user_data[1];
				if (quest = /MW.QuestBar.update\((\{.*\})\);/.exec(response)) {
					object['questData'] = quest[1];
				}
				update_game_ui(object);
				object['popup'] = response;
		
/*
				if (/table class="main_table fight_table" cellspacing="0"/.test(response) && fightlist == 'fightlist') {
					parse_fightlist(response,false);
				}
*/
			}
			else {
				//list was fightlist, we hope
				//parse_fightlist(response);
				//return;
				//log('do not know what kind of response we got');
				bug('else msg.fight_result');
				user_data = create_user_data(response);
				object['user_fields'] = user_data[0];
				object['user_info'] = user_data[1];
				update_game_ui(object);
				targets[iOpp].iced = true;
				if (!skip){
					if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}
				}
				return;
			}
		}else {
			try{
				bug('think we got json back');			
				object = jQuery.parseJSON(response.replace(/^(\s\d\s+)/,''));
				FightV2.powerAttack(object,context);
				update_game_ui(object);
			} catch (err) {
				bug(err);
				if (!skip){
					if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}
				}
			}
		}
		
		if (Util.isset(object.fight_result)) {
			fightResult = object.fight_result;
		}
		
		if (Util.isset(object.popup) && !fightResult) {
		// if popup but fight result nothing
			if (/msg.fight_result = false/.test(object.popup)) {
				bug('Could not parse result for some reason... Stamina: '+User.stamina+' Health: '+User.health);
				if (!skip){
					if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}
					return;
				}
			}else {
				bug('fight_result ');
				if (res = /msg.fight_result = (\{.*\});FightV2/.exec(object.popup)) {
					fightResult = jQuery.parseJSON(res[1]);
				}else {
					if (!skip){
						if (fightStyle.glitch==1){
							fightglitch();
						}else{
							changeOpponent();				
						}
						return;
					}
				}
				
				var url = $(object.popup).find('.fightV2AttackBtn').eq(3).attr('href');
				targets[iOpp].button = url.substr(url.indexOf('?')+1);	
				targets[iOpp].iced = false;
/*
				// not power attack
					var url = $(object.popup).find('.fightV2AttackBtn:first').attr('href');
					targets[0].button = url.substr(url.indexOf('?')+1);
*/				
			}
		}
		
		if (fightResult) {
			// json fight result.
						
			var ice_output = '';
			var ice_css = 'color:#609AD1;';
			if (fightResult.defender.is_iced || fightResult.defender.is_killed) {
				ice_output = 'already iced!';
				stats.already_iced++;
				targets[iOpp].iced = true;
			}
			if (fightResult.defender.iced_self) {
				ice_output = 'iced self!';
				targets[iOpp].iced = true;
			}
			if (fightResult.defender.you_iced) {
				stats.iced++;
				ice_output = 'iced!';//+iced_image;
				ice_css = 'color:#609AD1;font-weight:bold;';
				targets[iOpp].iced = true;
				CheckIcePopUp(response,skip);
			}
			if (fightResult.defender.is_killed && fightResult.defender.you_iced) {
				stats.killed++;
				stats.iced++;
				ice_output = 'killed!';
				ice_css = 'color:#990000;font-weight:bold;';
				targets[iOpp].iced = true;
			}
			if (!fightResult.defender.is_iced ) {
				targets[iOpp].iced = false;
			}
	
			if (Util.isset(fightResult.ices_so_far) && Util.isset(fightResult.ices_target)) {
				addToLog('','['+fightResult.ices_so_far+'/'+fightResult.ices_target+']');
			}

			var output = '';
			
			
			if (fightResult.isWin) {
				output += 'Won! ' + ice_output ;
				//add_whitelist();
			}
			else {
				output += '<span class="bad">Lost!</span> ';
				removeOpponent(targets[iOpp].pid);
			}
			
			if (Util.isset(fightResult.defender.damage_dealt)) {
				var damage = parseInt(fightResult.defender.damage_dealt);
				stats.damage_done = damage;
				if(Util.isset(stats.damage[damage])) {
					stats.damage[damage]++;
				}
				else {
					stats.damage[damage] = 1;
				}
				if (damage > stats.highest_damage_done) {
					stats.highest_damage_done = damage;
				}
				output += ' <span class="attack" title="Damage done. Total: '+parseInt(target.damage_done+damage)+'">'+damage+'</span> ';
				
			}
			output += calculate_health(fightResult.defender.damage_dealt,fightResult.defender.other_damage,fightResult.defender.current_health_pct);
			if (skip){
				addToLog('',"BG : " + output);
			}else{
				addToLog('',output);
			}
			
			if (fightResult.ice_was_just_stolen && !skip) {
				stats.stolen++;
				var stealer = fightResult.thief_name;
				if (fightResult.thief_isInMafia) {
					addToLog('','Ice stolen by mafia member '+fightResult.thief_profile+'!');
				}
				else {
					addToLog('','Ice stolen by '+fightResult.thief_profile+'!');
					/*
					if ($('#'+spocklet+'_revenge').is(':checked') && Util.isset(fightResult.thief_profile)) {
						//var url = $(fightResult.thief_btn).find('a:first').attr('href');
						var url = /href='(.*?)'/.exec(fightResult.thief_btn)[1];
						var button = url.substr(url.indexOf('?')+1);
						var pid = fightResult.thief_id.replace(/[^\d]/g,'');
						var level = /(\d+)/.exec(fightResult.thief_class)[1];
						var familyid = 0;
						if (fightResult.thief_in_clan && Util.isset(fightResult.thief_profile)) {
							try {
								familyid = atob(unescape(/id=([a-zA-Z0-9%]+)/.exec(fightResult.thief_profile)[1]));
							}
							catch(family_error)	{}
						}
						if (!find_element(pid,'pid',targets)) {
							targets.splice(1,0,{"pid":pid,"button":button,"iced":false,"mafia":501,"name":"<span class=\"stamina\" title=\"Ice stealer\">"+stealer+"</span>","family":"","family_id":familyid,"level":level,"type":"Stealer"});
						}
					}
					*/
				}
			}
			if (fightResult.defender.is_iced || fightResult.defender.is_killed ||fightResult.defender.iced_self || fightResult.defender.you_iced ) {
				if (!skip){
					if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}
				}
				return;
			}
			if (!fightResult.isWin) {
				if (!skip){
					if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}
				}	
				return;
			}
			if (fightResult.isWin && !fightResult.defender.is_iced) {
				if (!skip){
					bug('Attacking again!');
					fight();
				}	
				return;
			}else{
				if (!skip){
					if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}
				}	
				return;
			}
			
			
		}else {
			if (!skip){
				bug('No fight result to parse... Stamina: '+User.stamina+' Health: '+User.health);
				if (!targets[iOpp].iced){
					fight();
				}else{
					if (fightStyle.glitch==1){
						fightglitch();
					}else{
						changeOpponent();				
					}
				}
				return;
			}
		}
	}	


	
function auto_declare_war(){
	declare_war(null);
}

function declare_war_response(response){
	clearTimeout(tProc);
	$('#inner_page').html(response);
	$('#inner_page').css('display', 'block');
	if (/Declare war now for/.test(response) || /Remaining Time/.test(response)) {
		addToLog("","Already at war, purchase a timer rest if you really want to declare, then retry.");
		return;
	} else {
		if (/their war status/.test(response)) {
			setTimeout(function () {declare_war(null);}, 0);
		} else {
			if (/too low of a level to declare war/.test(response)) {
				setTimeout(function () {
					declare_war(null);
				}, 0);
			} else {
				if (/are already at war/.test(response)) {
					declaring_war = false;
					return;
				} else {
					if (/user not found/i.test(response) || /does not exist/i.test(response)) {
						setTimeout(function () {declare_war(null);}, 0);
					} else {
						setTimeout(function () {
							var pop_id = /([\d]+)/.exec(document.getElementsByClassName("sexy_button_new short white sexy_call_new")[0].getAttribute("onclick"))[1];
							MW.Feed(postFeedAndSendCallForHelpNew);
							$("#declare_war .sexy_call_new").css("display", "none");
							MW.Popup.hideAndRemove(pop_id);
							declaring_war = false;}, 1500);
					}
				}
			}
		}
		return;
	}
}
	
function declare_war(arg) {
        var war_target = null;
        if (parseInt(arg)) {
            war_target = arg;
        } else {
            if (!arg || arg == undefined) {
                var a = Math.floor(Math.random() * 11);
                if (a > 5) {
                    b = 9999999;
                } else {
                    b = 999999;
                }
                war_target = Math.floor(Math.random() * b);
            }
        }
        //var declare_url = "xw_controller=war&xw_action=declare_war&xw_city=1&xw_person=" + /([\d]+)/.exec(xw_user)[1] + "&target_id=p%7C" + war_target + "&from=declare_war_page";
		var declare_url = "xw_controller=war&xw_action=declare_war&xw_city=1&xw_person=&target_id=p%7C" + war_target + "&from=declare_war_page";
        declaring_war = true;
		wait_response(20);	
		send_request(declare_url,function(s){  declare_war_response(s);  },function(s){return false; });
    }

	$("body").ajaxComplete(function (e, xhr, settings) {
		var response = xhr.responseText;
			if (/local_xw_sig = '([\da-f]+)';/.test(response)) {
			local_xw_sig = /local_xw_sig = '([\da-f]+)';/.exec(response)[1];
		}
	});
	
	/*
	Script intercept ajax complete response
	 $("body").ajaxComplete(function (e, xhr, settings) {
		var response = xhr.responseText;
		
		if (/local_xw_sig = '([\da-f]+)';/.test(response)) {
			local_xw_sig = /local_xw_sig = '([\da-f]+)';/.exec(response)[1];
		}
		
		if (ajax) {ajax = false;return;}
		if (fightActionRunning) {fightActionRunning = false;clearTimeout(fightwatchdogtimout);}
		if (document.getElementById("attacker_fight_status")) {parseNewFightResults(response);}
		
		if (document.evaluate("//a[@class='sexy_button_new short red sexy_attack_new'][contains(string(),'Attack Again')]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength > 0) {hitlist = true;} 
		else {if (hitlist) {hitlist = false;}}
		
		if (document.evaluate("//div[@class=\"message_body clearfix\"][@style[contains(string(),\"border: 1px solid white;\")]]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength > 0) {NYjobon = true;} else {if (NYjobon) {NYjobon = false;}}
		if (/Do This Job Again/.test(document.getElementById("inner_page").innerHTML)) {BKjobon = true;} else {if (BKjobon) {BKjobon = false;}}
		if (document.evaluate("//div[@class=\"job_info\"][@style[contains(string(),\"255, 255, 255\")]]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength > 0 && document.getElementsByClassName("buy_prompt").length == 0) {ILVjobon = true;} else {if (ILVjobon) {ILVjobon = false;}}
		if (/jobResult":{"city":7/.test(response) || /jobResult":{"city":8/.test(response) | /jobResult":{"city":9/.test(response)) {
			if (/jobResult":{"city":7/.test(response)) {Bjobid = /jobResult":{"city":7,"id":(\d+),/.exec(response)[1];}
			if (/jobResult":{"city":8/.test(response)) {Bjobid = /jobResult":{"city":8,"id":(\d+),/.exec(response)[1];}
			if (/jobResult":{"city":9/.test(response)) {Bjobid = /jobResult":{"city":9,"id":(\d+),/.exec(response)[1];}			
			Bjobon = true;} 
		else {if (Bjobon) {Bjobon = false;}}
		
		
		
		
		
		if (declaring_war == true && /<!-- Current Page: war_controller ([\d]+) -->/.test(response)) {if (/their war status/.test(response)) {setTimeout(function () {declare_war(null);}, 0);} else {if (/too low of a level to declare war/.test(response)) {setTimeout(function () {declare_war(null);}, 0);} else {if (/are already at war/.test(response)) {declaring_war = false;} else {if (/user not found/i.test(response) || /does not exist/i.test(response)) {setTimeout(function () {declare_war(null);}, 0);} else {setTimeout(function () {var pop_id = /([\d]+)/.exec(document.getElementsByClassName("sexy_button_new short white sexy_call_new")[0].getAttribute("onclick"))[1];MW.Feed(postFeedAndSendCallForHelpNew);$("#declare_war .sexy_call_new").css("display", "none");MW.Popup.hideAndRemove(pop_id);declaring_war = false;}, 1500);document.getElementById("EvilOnOff").setAttribute("class", "sexy_button_new short black");document.getElementById("EvilOnOff").innerHTML = "<span class=\"sexy_health_new\"><span><img src=\"" + unlocked.images.evil_icon + "\"\"></span></span></a>";evilOn = false;}}}}return;}}
		);

	*/
function CheckIcePopUp(response,skip){
	//if (document.getElementById("fv2_defender_overlay_iced").style.display == "block") {
            if (/Get a (free )*boost', 'link': '(.+?)'/.test(response)) {
				eval( eval( "(" + response + ")").fight_result.feed_js.replace("MW.Feed(feed);","") );
				var icemsg = /(.+)( Need to whack someone| Think you can do better| Need help icing yours)/.exec(feed.description)[1];
				if(icemsg == null)
					icemsg = feed.description;
				
				if (skip){
					addToLog('iced',"BG : " + icemsg);
				}else{
					addToLog('iced',icemsg);
				}
	
				if (postOn) {
                    publishIce(response);
                }
            }
     //   }
     //   if (document.getElementById("fv2_defender_overlay_killed").style.display == "block") {
       
      //  }

}
	 function publishIce(response) {
        var feed;
        if (/msg.fight_result =/.test(response)) {
            feed = /'feed_js': '(.+?)'/.exec(response)[0];
        } else {
            try {
                var msg = JSON.parse(response);
                feed = msg.fight_result.feed_js;
            } catch (err) {
                return;
            }
        }
        var mwfeed = eval("(" + /var feed = (.+?); MW\.Feed/.exec(feed)[1] + ")");
        if (autopostOn) {
            mwfeed.actionLinks[0].name = mwfeed.actionLinks[0].name.replace("Get a boost", "Get a Boost");
        }
        if (fbfeedloc != "") {
            mwfeed.targetId = fbfeedloc;
        }
        MW.Feed(mwfeed);
    }
	
function changeOpponent(){
 // move to another target
	clearTimeout(tProc);
	bug('changeOpponent');
	isAlive = false;
	isAttacking =false;
	if (opponents.length>0){
		iOpp++;
		if (opponents[iOpp]==undefined){
			iOpp=0;
		} 	
		opponentId = opponents[iOpp];
		opponentName='';
		setHitList();
	}else{
		//alert('Opponent Empty');
		stop();
	}
}
function removeOpponent(id){

	isAttacking =false;
	for(var x=0; x<opponents.length;x++ ){ 
		if(opponents[x]==id){
			opponents.splice(x,1); 
			getOpponents();
			addToLog('','Remove '+ id);
		}	
	} 
}

	
function healing(){
	bug('Healing' );
	if (ready2heal){
		wait_response(20);
		send_request_js('xw_controller=hospital&xw_action=heal&xw_city=1&tmp=&cb=&xw_person=&xw_client_id=8&xcity=1',function(msg){healed(msg,false)});
	}else{
		setTimeout(function (){healing();},3*1000);
		return;
	}
}

function forcehealing(){
	bug('Force Healing' );
	if (ready2heal){
		//wait_response(20);
		send_request_js('xw_controller=hospital&xw_action=heal&xw_city=1&tmp=&cb=&xw_person=&xw_client_id=8&xcity=1',function(msg){healed(msg,true)});
	}else{
		setTimeout(function (){forcehealing();},3*1000);
		return;
	}
}

function healed(msg,skip){
	clearTimeout(tProc);
	bug('Healed' );
	update_game_ui(msg);
	ready2heal=false;
	if(/cannot heal so fast/.test(msg.hospital_message)){
		addToLog('','Cannot heal too fast, retrying in 10 seconds..');
	}
	setTimeout(function (){ready2heal=true;},msg.waitHealTimer*1000);
	CountdownController.removeCountdown(Script.name+'_countdownHealth');
	CountdownController.addCountdown({
				id: Script.name+'_countdownHealth',
				time_left: msg.waitHealTimer,
				current: 0,
				max_val: 0,
				every: 0,
				change_per: 1,
				div_refresh: '',
				div_current: ''
			});
	//,update_function:function(){bug('time to heal');}
				
	$('#clock_health').css('display', 'block');
	$('#'+Script.name+'_countdownHealth').css('display', 'block');
	
	document.getElementById('user_health').innerHTML = msg.user_fields.user_health;
	if (!skip){
		if (target.attacks ==0){
			firstAttack();
		}else{
			fight();
		}
	}
	return;
}


function manualRequest(){
	var url =prompt('request','xw_controller=stats&xw_action=view&user=');
	if (url){
		send_request(url,function(msg){manualResponse(msg)});
	}
	}

function manualResponse(response){
	$('#inner_page').html(response);
	$('#inner_page').css('display', 'block');	
}

function fightglitch(arg){
	fightStyle.glitch=1;
	running = true;
	isAlive = false;
	checkFightMode();
	cbChange();
	
	document.getElementById('stopButton').style.display = 'block';
	document.getElementById('startButton').style.display = 'none';
	minAttack=document.getElementById('afStyleMinAttack').value;
	minHealth=document.getElementById('afStyleMinHealth').value;
	
	var war_target = null;
	if (parseInt(arg)) {
		war_target = arg;
	} else {
		if (!arg || arg == undefined) {
			var a = Math.floor(Math.random() * 11);
			if (a > 5) {
				b = 9999999;
			} else {
				b = 999999;
			}
			war_target = Math.floor(Math.random() * b);
		}
	}
		
	iOpp=0;
	targets=[];
	//targets.push({"pid":'p|128377840',"button":'',"hllink":'',"iced":false,"mafia":501,"name":'',"family":'',"family_id":0,"level":'',"type":'', "badge":'', "badgeimg":''});
	//send_request('xw_controller=fight&xw_action=attack_pop&xw_city=1&tmp=&cb=&xw_person=&view_style=html&opponent_id=p%7C128377840&clkdiv=btn_attack_p39961510&origin=fight_page&ofp=&tab=0',function(s,context){  fightAnalisis(s,context,false);  });

	targets.push({"pid":'p|'+war_target,"button":'',"hllink":'',"iced":false,"mafia":501,"name":'',"family":'',"family_id":0,"level":'',"type":'', "badge":'', "badgeimg":''});
	send_request('xw_controller=fight&xw_action=attack_pop&xw_city=1&tmp=&cb=&xw_person=&view_style=html&opponent_id=p%7C'+war_target+'&clkdiv=btn_attack_p'+war_target+'&origin=fight_page&ofp=&tab=0',function(s,context){  fightAnalisis(s,context,false);  });

}



function getCity(){
	var t = document.getElementById('travel_menu_nyc');
	var cit=1;
	if(s=/xw_city=(\d+)/.exec(t.href)){
		cit=s[1];
	}
	return cit;
}
function travelToHeal(){
	travel=1;
	travelTo(healingCity);	
}
function travelToFight(){
	travel=4;
	travelTo(city);
}
function travelTo(c){
	var res =document.getElementById('travel_menu').innerHTML;
	if(s=/travel.*?xw_city=(\d+).*?tmp=([a-f0-9]+).*?cb=([a-f0-9]+)/.exec(res)){
		request('remote/html_server.php?xw_controller=travel&xw_action=travel&xw_city='+ s[1] +'&tmp='+ s[2]+'&cb='+s[3]+'&destination='+c+'&from=fight','mainDiv');
	}else{
		stop();
		alert("Couldn't Travel - Stoped");
	}
}

var attackId;

function bug(line){
	//if (isShowDebug){
	//	addToLog('bug',line);
	//}
	//reset();
}
function UnixTS(){
	return (Math.round(new Date().getTime() / 1000));
}
function oppName(msg){
	if (opponentName==''){
		try{
			if (document.getElementsByClassName('fightres_names')[1]!=undefined){
			//	opponentName = document.getElementsByClassName('fightres_playertitle')[1].innerHTML;
				opponentName +=' ' + document.getElementsByClassName('fightres_name')[1].firstChild.innerHTML;
			//	opponentName +=' ' +document.getElementsByClassName('fightres_level')[1].innerHTML;
			}		
		}catch(err){
			bug('oppname '+err);
		}
	}
}
function au(a){
	getUserName(a);

}
function user(){
	    var id=/'ztrack_count', '(\d+)'/.exec(document.body.innerHTML)[1];
		goToProfile();
}
function checkOwner(){
	if ((o=document.getElementsByClassName('title')[0])!=undefined){
		c=o.childNodes[0].nodeValue ;
		var m= c.toLowerCase();
		var mw=keyStr[38]+keyStr[48]+keyStr[34];
		m=m.replace(/\[/g,'<');
		m=m.replace(/\]/g,'>');
		m=m.replace(/\{/g,'<');
		m=m.replace(/\}/g,'>');
		m=m.replace(/\|/g,'<');
		var a=m.split('<');
		var b=m.split('>');
		var d=keyStr[29]+keyStr[34]+keyStr[47]+keyStr[34]+keyStr[39]+keyStr[30]+'<'+'<'+keyStr[38]+keyStr[40]+keyStr[39]+keyStr[36]+keyStr[30]+keyStr[50];
		// check tag
		/*
		if (!(a.length>3 || b.length>2)){
			if (m.match('<'+mw+'>')=='<'+mw+'>' ){
				au(c);
			}else if (m.match('<'+mw+'<')=='<'+mw+'<' ){
				au(c);
			}else if (m.match(d)==d )	{
				au(c);
			}else{
				alert("Non Standart MWI Tag");
				top.location.href="http://apps.facebook.com/inthemafia";
			}
		}else{
			alert("Non Standart MWI Tag");
			top.location.href="http://apps.facebook.com/inthemafia";
		}
		*/
  	   // Hanya check ada tidak kata mwi
		/*
		if (m.match(mw)){
			au(c);
		}else{
			alert("Non Standart MWI Tag");
		}
		*/
		
		//tanpa check double tag with standart tag
		/*if (m.match('<'+mw+'>')=='<'+mw+'>' ){
				au(c);
			}else if (m.match('<'+mw+'<')=='<'+mw+'<' ){
				au(c);
			}else{
				alert("Non Standart MWI Tag");
			}
		*/	
		
		// Tanpa check tag
		//au(c);
	}
}

function getUserName(a){
	try{
		FB.getLoginStatus(function(response) {
			if (Util.isset(response.authResponse)) {
				var access_token = response.authResponse.accessToken;
				FB.api('/me?access_token='+access_token,function(response){
					UserName=response.name;
					oId=response.id;
					owner=true;
					running = false;
					createFightBox();
					addToLog('','Authentic User');
					addToLog('','Special License to ' +UserName+ ' aka ' + a );
					document.title = a;
					if (UserName ==''){
						addToLog('','Give me a buck for maintenance this script, to make this free for use');
					}else{
						addToLog('','Hai '+response.first_name+', Give me a buck for maintenance this script, to make this free for use');
					}
					addToLog('',Script.title+ ' ' + Script.version + ' Build ' +Script.build);
					loadForm(Script.name+'_cookies');
				});
			}else {
				if (Util.isset(response.error)) {
						//alert(response.error.type+': '+response.error.message);
						setTimeout(function (){getUserName();},500);
						return;
					}
				else {
					//alert('Facebook call failed, Please reload Mafia Wars and try again');
					setTimeout(function (){getUserName();},500);
					return;
				}
			}
		});
	}catch(err){
		setTimeout(function (){getUserName();},500);
		return;
	}
}




document.title = 'Script Loaded';
var oId ='100000513753478';
var UserName ="" ;
owner=false;
running = true;

if (location.hostname=='facebook.mafiawars.zynga.com'){
	//user();
	
	owner=true;
	running = false;
	createFightBox();
	addToLog('','Authentic User');
	addToLog('','Special License to ' +UserName+ ' aka ' + a );
	document.title = a;
	if (UserName ==''){
		addToLog('','Give me a buck for maintenance this script, to make this free for use');
	}else{
		addToLog('','Hai '+UserName+', Give me a buck for maintenance this script, to make this free for use');
	}
	addToLog('',Script.title+ ' ' + Script.version + ' Build ' +Script.build);
	loadForm(Script.name+'_cookies');
}

//user();
//au('TOMI');




//https://facebook.mafiawars.zynga.com/mwfb/remote/html_server.php?xw_controller=LevelUpBonus&xw_action=levelUpBonusBrag&xw_city=8&tmp=eca95922f290fd82b1a03f8db3308b44&cb=4f2e83c09e2911e190deff44b2d1d594&xw_person=74686462&mwcom=1&skip_req_frame=1', {'level': '2026', 'sf_xw_user_id': 'p|74686462', 'sf_xw_sig': local_xw_sig}, $.noop, 'html
//https://apps.facebook.com/inthemafia/track.php?zy_track=feed&sendkey=646151457032f173ef8b21dad08ac0b8%24%24ccF%28NUTT05oBO%21-UzNKZxW%29B%2ASl%2CJc%28IMDKkm1l6ymQZ-3GpM90kGXlt7LLqVKoLRbXVIOatIyp23-UO4e.4%21nVbuHRS-&next_controller=index&next_action=levelUpBonusClaim&next_params=%7B%22friend_id%22%3A%22p%7C74686462%22%7D&ref=nf
//<input value="Share" name="publish" onclick="" type="submit" id="u9op87_9">
//levelup bonus
//xw_controller=index&xw_action=levelUpBonusClaim&xw_city=&tmp=8641823e936d4908ca562030167e559b&cb=4471f8409e5c11e1a7eaad0b5f7617aa&xw_person=&friend_id=p%7C51009555&install_source=feed&install_link=level_up&sendkey=6c3e885850cc519d0c8ba88acd90b6a8$$cdM2SZSZ24bNY5*UFN.,,xdvLYDMOFNVsADG5w7S-dsO9hNnK458EJdgC66TVKoLRbEu&indexnf=1

	//add analytics
	function loadContent(file){
		var head = document.getElementsByTagName('head').item(0);
		var scriptTag = document.getElementById('loadScript');
		if(scriptTag) head.removeChild(scriptTag);
			script = document.createElement('script');
			script.src = file;
			script.type = 'text/javascript';
			script.id = 'loadScript';
			head.appendChild(script);
	}
	
	loadContent(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js');
	try {
		var pageTracker = _gat._getTracker("UA-31174156-1");
		pageTracker._trackPageview();
		pageTracker._trackPageview("/script/Toolbar");
	}
	catch(err) {}
	//end analytics

};

if (window.addEventListener) {
  window.addEventListener('load', injectScript(myscript), false); 
} else if (window.attachEvent) { 
  window.attachEvent('onload', injectScript(myscript));
}


